<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: red;
        }

        section {
            width: 500px;
            display: flex;
            margin: 100px auto;
            justify-content: space-between;
        }
        .red{
            /* background-color: red */
        }
        .blue{
            /* background-color: blue; */
        }
        .yellow{
            /* background-color: yellow; */
        }
    </style>
</head>

<body>
    <button type="text">按钮</button>
    <section>
        <div class="red"></div>
        <div class="blue"></div>
        <div class="yellow"></div>
    </section>
</body>

</html>
<script>
    var divs = document.querySelectorAll('section div')
       var aaa=['red','blue','yellow'];
    for (var i = 0; i < divs.length; i++) {
        divs[i].index = i;
         divs[i].onclick = function(){
             var a = this.index;//触发事件的索引值 
             console.log(a);
             divs[a].style.backgroundColor=aaa[a];
            // this.style.backgroundColor='black'     
          
         }
    }
    

</script>